package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map<String, Object> wxLogin(String code) {
        //包含用户在微信开放平台账号下的*唯一标识 OpenID
        WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
        try {
            //需要通过code,appid,appsecret换取openid，但是appid,appsecret是我们自己的
            //WxMaConfig config = this.getWxMaConfig();
            //params.put("appid", config.getAppid());
            //params.put("secret", config.getSecret());
            //我们利用多态自定义父类引用WxMaService的子类WxMaServiceImpl对象，
            // 并设置其WxMaConfig实现类WxMaDefaultConfigImpl的对象属性
            //this对象是父类引用对象，调方法时调用子类的方法及获取我们定义的WxMaDefaultConfigImpl实现类
            //我们在其中设置了Appid和Secret，那么就能获取他们
            wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
            System.out.println("ddddddddd");
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //获取openid
        String openid = wxMaJscode2SessionResult.getOpenid();
        //根据由code，appid，secret生成的每一个用户的独有的openid，根据openId查出用户信息
        UserInfo userInfo = this.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        //从未登陆过，注册
        if(userInfo==null){
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("听友:"+System.currentTimeMillis());
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            this.save(userInfo);
            //首次注册到账100元，利用rabbitmp给account模块发送消息
            rabbitService.sendMessage(MqConst.EXCHANGE_USER,MqConst.ROUTING_USER_REGISTER,userInfo.getId());
        }
        //登录后在缓存中存一个token，并将token返回放入请求中，之后通过请求头中的token获取到缓存中的userInfo
        //如果key删除或者过期，切面返回异常重新登陆，重新设置token返回前端
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX+token;
        redisTemplate.opsForValue().set(userLoginKey,userInfo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        return map;
    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {
        //	创建对象
        UserInfoVo userInfoVo = new UserInfoVo();
        //	获取用户信息
        UserInfo userInfo = this.getById(userId);
        //	属性拷贝
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }

    @Override
    public void updateUser(UserInfoVo userInfoVo, Long userId) {
        //	更新用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        this.userInfoMapper.updateById(userInfo);
    }
}
